<template>
  <div class="admin-challenges">
    <!-- 猫咪动画 - 移到顶部 -->
    <div class="cat-animation-container">
      <div class="cat">
        <div class="cat-head">
          <div class="cat-ears">
            <div class="cat-ear left"></div>
            <div class="cat-ear right"></div>
          </div>
          <div class="cat-face">
            <div class="cat-eyes">
              <div class="cat-eye left"></div>
              <div class="cat-eye right"></div>
            </div>
            <div class="cat-nose"></div>
            <div class="cat-mouth"></div>
            <div class="cat-whiskers">
              <div class="whisker w1"></div>
              <div class="whisker w2"></div>
              <div class="whisker w3"></div>
              <div class="whisker w4"></div>
              <div class="whisker w5"></div>
              <div class="whisker w6"></div>
            </div>
          </div>
        </div>
        <div class="cat-body">
          <div class="cat-tail"></div>
          <div class="cat-paws">
            <div class="cat-paw"></div>
            <div class="cat-paw"></div>
          </div>
        </div>
      </div>
      <div class="yarn-ball"></div>
      <div class="eco-message">
        <span>欢迎来到任务管理页面 - 保护环境，从低碳生活开始</span>
        <div class="eco-icon">🌱</div>
      </div>
    </div>
    
    <!-- 页面通知 -->
    <div class="notification-container" v-if="notification.show">
      <div :class="['notification', 'notification-' + notification.type]">
        <span class="notification-message">{{ notification.message }}</span>
        <button class="notification-close" @click="notification.show = false">×</button>
      </div>
    </div>
    
    <!-- 顶部工具栏 -->
    <div class="toolbar">
      <div class="search-box">
        <input 
          type="text" 
          v-model="searchQuery" 
          placeholder="搜索任务名称、类型..." 
          class="admin-form-input search-input"
          @input="handleSearch"
        >
        <button class="search-btn">
          🔍
        </button>
      </div>
      
      <div class="filter-options">
        <select v-model="statusFilter" class="admin-form-input filter-select" @change="handleFilter">
          <option value="">全部状态</option>
          <option value="active">进行中</option>
          <option value="completed">已结束</option>
          <option value="upcoming">即将开始</option>
        </select>
        
        <select v-model="categoryFilter" class="admin-form-input filter-select" @change="handleFilter">
          <option value="">全部类型</option>
          <option value="daily">日常生活</option>
          <option value="energy">节能减排</option>
          <option value="transport">绿色出行</option>
          <option value="recycling">垃圾分类</option>
          <option value="water">节约用水</option>
        </select>
      </div>
      
      <div class="action-buttons">
        <router-link to="/admin/challenges/new" class="admin-btn admin-btn-primary">
          新建任务
        </router-link>
        <button class="admin-btn" @click="exportData">导出数据</button>
      </div>
    </div>
    
    <!-- 加载状态 -->
    <div class="loading-container" v-if="loading">
      <div class="loading-spinner"></div>
      <p>正在加载任务数据...</p>
    </div>
    
    <!-- 任务列表 -->
    <div class="challenges-list" v-else>
      <table class="admin-table">
        <thead>
          <tr>
            <th>任务名称</th>
            <th style="width: 100px;">类型</th>
            <th style="width: 100px;">难度</th>
            <th style="width: 120px;">开始时间</th>
            <th style="width: 120px;">结束时间</th>
            <th style="width: 100px;">状态</th>
            <th style="width: 100px;">参与人数</th>
            <th style="width: 150px;">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="task in filteredTasks" :key="task.id">
            <td>{{ task.title }}</td>
            <td>{{ getCategoryText(task.category) }}</td>
            <td>
              <div class="difficulty-wrapper">
                <span 
                  v-for="n in 3" 
                  :key="n" 
                  :class="['difficulty-dot', n <= (task.difficulty + 1) ? 'active' : '']"
                ></span>
              </div>
            </td>
            <td>{{ formatDate(task.startTime) }}</td>
            <td>{{ formatDate(task.endTime) }}</td>
            <td style="padding: 5px 10px; font-weight: bold;">
              <div v-if="task.taskStatus === 0" style="color: #fa8c16; display: inline-block;">即将开始</div>
              <div v-else-if="task.taskStatus === 1" style="color: #1890ff; display: inline-block;">进行中</div>
              <div v-else-if="task.taskStatus === 2" style="color: #52c41a; display: inline-block;">已结束</div>
              <div v-else style="color: #555; display: inline-block;">未知状态</div>
            </td>
            <td>{{ task.participants }}</td>
            <td class="actions-cell">
              <div class="actions-wrapper">
                <button class="action-btn edit-btn" @click="showEditModal(task)">
                  编辑
                </button>
                <button 
                  class="action-btn delete-btn" 
                  @click="showDeleteConfirm(task)"
                >
                  删除
                </button>
              </div>
            </td>
          </tr>
          <tr v-if="filteredTasks.length === 0">
            <td colspan="9" class="empty-message">
              <div class="empty-content">
                <div class="empty-icon">📝</div>
                <div class="empty-text">
                  {{ searchQuery || statusFilter || categoryFilter ? '没有找到匹配的任务' : '暂无任务数据' }}
                </div>
                <div class="empty-action" v-if="searchQuery || statusFilter || categoryFilter">
                  <button class="admin-btn" @click="resetFilters">重置筛选</button>
                </div>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    
    <!-- 分页器 -->
    <div class="pagination">
      <div class="pagination-info">
        共 {{ totalItems }} 项，每页 {{ pageSize }} 项，当前第 {{ currentPage }} 页
      </div>
      <div class="pagination-buttons">
        <button 
          :disabled="currentPage === 1" 
          @click="changePage(currentPage - 1)"
          class="pagination-btn"
        >
          上一页
        </button>
        <button 
          v-for="page in displayedPages" 
          :key="page" 
          :class="['pagination-btn', page === currentPage ? 'active' : '']"
          @click="changePage(page)"
        >
          {{ page }}
        </button>
        <button 
          :disabled="currentPage === totalPages" 
          @click="changePage(currentPage + 1)"
          class="pagination-btn"
        >
          下一页
        </button>
      </div>
    </div>
    
    <!-- 删除确认对话框 -->
    <div class="modal-overlay" v-if="showDeleteModal">
      <div class="modal-container">
        <div class="modal-header">
          <h3>确认删除</h3>
        </div>
        <div class="modal-body">
          <p>您确定要删除任务 <strong>{{ selectedTask.title }}</strong> 吗？</p>
          <p class="warning-text">此操作不可逆，删除后数据将无法恢复。</p>
        </div>
        <div class="modal-footer">
          <button class="admin-btn" @click="cancelDelete">取消</button>
          <button class="admin-btn admin-btn-danger" @click="confirmDelete">确认删除</button>
        </div>
      </div>
    </div>
    
    <!-- 编辑弹窗 -->
    <div class="modal-overlay" v-if="editModalVisible">
      <div class="modal-container edit-modal">
        <div class="modal-header">
          <h3>{{ editingTask.id ? '编辑任务' : '新建任务' }}</h3>
          <button class="modal-close-btn" @click="cancelEdit">×</button>
        </div>
        <div class="modal-body">
          <div class="loading-container" v-if="editLoading">
            <div class="loading-spinner"></div>
            <p>正在加载任务详情...</p>
          </div>
          <div class="error-container" v-else-if="editError">
            <div class="error-icon">❌</div>
            <h3>出错了</h3>
            <p>{{ editError }}</p>
          </div>
          <div class="edit-form" v-else>
            <!-- 表单基本信息部分 -->
            <div class="form-row">
              <div class="admin-form-item">
                <label class="admin-form-label required">任务名称</label>
                <input
                  type="text"
                  v-model="editForm.title"
                  class="admin-form-input"
                  placeholder="请输入任务名称"
                >
                <div class="admin-form-error" v-if="editErrors.title">{{ editErrors.title }}</div>
              </div>
            </div>
            
            <div class="form-row two-col">
              <div class="admin-form-item">
                <label class="admin-form-label required">任务类型</label>
                <select v-model="editForm.category" class="admin-form-input" disabled>
                  <option value="">请选择类型</option>
                  <option value="daily">日常生活</option>
                  <option value="energy">节能减排</option>
                  <option value="transport">绿色出行</option>
                  <option value="recycling">垃圾分类</option>
                  <option value="water">节约用水</option>
                </select>
                <div class="admin-form-error" v-if="editErrors.category">{{ editErrors.category }}</div>
                <div class="admin-form-helper">任务类型创建后不可修改</div>
              </div>
              
              <div class="admin-form-item">
                <label class="admin-form-label required">难度级别</label>
                <div class="difficulty-selector">
                  <div 
                    v-for="(level, index) in difficultyLevels" 
                    :key="index" 
                    :class="['difficulty-option', editForm.difficulty === index ? 'active' : '']"
                    @click="editForm.difficulty = index"
                  >
                    {{ level }}
                  </div>
                </div>
                <div class="admin-form-error" v-if="editErrors.difficulty">{{ editErrors.difficulty }}</div>
              </div>
            </div>
            
            <div class="form-row two-col">
              <div class="admin-form-item">
                <label class="admin-form-label required">开始时间</label>
                <input
                  type="date"
                  v-model="editForm.startTime"
                  class="admin-form-input"
                >
                <div class="admin-form-error" v-if="editErrors.startTime">{{ editErrors.startTime }}</div>
              </div>
              
              <div class="admin-form-item">
                <label class="admin-form-label required">结束时间</label>
                <input
                  type="date"
                  v-model="editForm.endTime"
                  class="admin-form-input"
                >
                <div class="admin-form-error" v-if="editErrors.endTime">{{ editErrors.endTime }}</div>
              </div>
            </div>
            
            <div class="form-row">
              <div class="admin-form-item">
                <label class="admin-form-label required">任务描述</label>
                <textarea
                  v-model="editForm.description"
                  class="admin-form-input description-input"
                  placeholder="请输入任务描述"
                  rows="4"
                ></textarea>
                <div class="admin-form-error" v-if="editErrors.description">{{ editErrors.description }}</div>
              </div>
            </div>
            
            <div class="form-row">
              <div class="admin-form-item">
                <label class="admin-form-label">状态</label>
                <div class="status-selector">
                  <label class="status-option">
                    <input type="radio" v-model="editForm.status" value="upcoming">
                    <span class="status-label">即将开始</span>
                  </label>
                  <label class="status-option">
                    <input type="radio" v-model="editForm.status" value="active">
                    <span class="status-label">进行中</span>
                  </label>
                  <label class="status-option">
                    <input type="radio" v-model="editForm.status" value="completed">
                    <span class="status-label">已结束</span>
                  </label>
                </div>
              </div>
            </div>
            
            <div class="form-row">
              <div class="admin-form-item">
                <label class="admin-form-label required">积分奖励</label>
                <input
                  type="number"
                  v-model.number="editForm.pointsReward"
                  class="admin-form-input"
                  min="0"
                  placeholder="完成任务后获得的积分数量"
                >
                <div class="admin-form-error" v-if="editErrors.pointsReward">{{ editErrors.pointsReward }}</div>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="admin-btn" @click="cancelEdit">取消</button>
          <button class="admin-btn admin-btn-primary" @click="saveEdit" :disabled="editLoading">保存</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getTaskList, deleteTask, getTaskDetail, updateTask } from '@/api/task.js'

export default {
  name: 'AdminTasks',
  data() {
    return {
      tasks: [],
      loading: false,
      searchQuery: '',
      statusFilter: '',
      categoryFilter: '',
      currentPage: 1,
      pageSize: 10,
      totalItems: 0,
      showDeleteModal: false,
      selectedTask: {},
      
      // 页面通知系统
      notification: {
        show: false,
        message: '',
        type: 'success', // success, error, info
        timeout: null
      },
      
      // 编辑相关数据
      editModalVisible: false,
      editingTask: {},
      editLoading: false,
      editError: null,
      editForm: {
        title: '',
        category: '',
        difficulty: 1,
        startTime: '',
        endTime: '',
        description: '',
        status: 'active',
        pointsReward: 100
      },
      editErrors: {},
      difficultyLevels: ['初级', '中级', '高级']
    }
  },
  computed: {
    filteredTasks() {
      let result = [...this.tasks]
      
      // 添加调试日志
      console.log('原始任务列表:', JSON.stringify(this.tasks.map(c => ({
        id: c.id,
        title: c.title,
        taskStatus: c.taskStatus,
        typeof_taskStatus: typeof c.taskStatus
      }))));
      
      // 搜索过滤
      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase()
        result = result.filter(task => 
          task.title.toLowerCase().includes(query) || 
          this.getCategoryText(task.category).toLowerCase().includes(query)
        )
      }
      
      // 状态过滤
      if (this.statusFilter) {
        // 将字符串状态转换为数字状态
        let numStatus = null;
        if (this.statusFilter === 'upcoming') {
          numStatus = 0;
        } else if (this.statusFilter === 'active') {
          numStatus = 1;
        } else if (this.statusFilter === 'completed') {
          numStatus = 2;
        }
        
        // 使用数字状态进行过滤
        if (numStatus !== null) {
          console.log('按状态过滤:', this.statusFilter, '对应数字状态:', numStatus);
          result = result.filter(task => {
            console.log(`任务${task.id} 状态: ${task.taskStatus}, 匹配: ${task.taskStatus === numStatus}`);
            return task.taskStatus === numStatus;
          });
        }
      }
      
      // 类型过滤
      if (this.categoryFilter) {
        result = result.filter(task => task.category === this.categoryFilter)
      }
      
      // 再次记录过滤后的结果
      console.log('过滤后的任务列表:', JSON.stringify(result.map(c => ({
        id: c.id,
        title: c.title,
        taskStatus: c.taskStatus
      }))));
      
      return result
    },
    totalPages() {
      return Math.ceil(this.totalItems / this.pageSize)
    },
    displayedPages() {
      // 根据"少于20条显示1个按钮，少于40显示2个按钮"的规则
      // 计算应该显示多少个页码按钮
      const maxButtons = Math.ceil(this.totalItems / 20);
      const pages = [];
      
      // 最多显示maxButtons个按钮，但不能超过实际的总页数
      const buttonsToShow = Math.min(maxButtons, this.totalPages);
      
      for (let i = 1; i <= buttonsToShow; i++) {
        pages.push(i);
      }
      
      return pages;
    }
  },
  created() {
    this.fetchTasks()
  },
  methods: {
    fetchTasks() {
      this.loading = true
      
      // 构建查询参数
      const params = {
        pageNo: this.currentPage,
        pageSize: this.pageSize
      }
      
      // 添加搜索条件
      if (this.searchQuery) {
        params.taskName = this.searchQuery
      }
      
      // 添加状态过滤
      if (this.statusFilter) {
        // 将状态转换为API需要的格式
        if (this.statusFilter === 'active') {
          params.taskStatus = 1
        } else if (this.statusFilter === 'completed') {
          params.taskStatus = 2
        } else if (this.statusFilter === 'upcoming') {
          params.taskStatus = 0
        }
      }
      
      // 添加类型过滤
      if (this.categoryFilter) {
        params.categoryId = this.getCategoryId(this.categoryFilter)
      }
      
      console.log('发送API请求参数:', JSON.stringify(params));
      
      // 调用API获取数据
      getTaskList(params)
        .then(response => {
          console.log('获取任务列表成功:', response)
          
          // 详细输出响应结构
          console.log('响应结构:', 
            'response.data存在:', !!response.data, 
            'response.data是数组:', Array.isArray(response.data),
            'response.data.list存在:', response.data && !!response.data.list,
            'response.data.list是数组:', response.data && Array.isArray(response.data.list)
          );
          
          // 处理响应数据
          let taskList = []
          let totalCount = 0
          
          // 尝试从不同结构中提取数据
          if (response.data && response.data.list && Array.isArray(response.data.list)) {
            taskList = response.data.list
            totalCount = response.data.total || 0
            console.log('使用 response.data.list, 条目数:', taskList.length);
          } else if (response.data && Array.isArray(response.data)) {
            taskList = response.data
            console.log('使用 response.data 数组, 条目数:', taskList.length);
          } else if (response.result && Array.isArray(response.result)) {
            taskList = response.result
            console.log('使用 response.result 数组, 条目数:', taskList.length);
          } else if (response.data && response.data.result && Array.isArray(response.data.result)) {
            taskList = response.data.result
            totalCount = response.data.total || 0
            console.log('使用 response.data.result 数组, 条目数:', taskList.length);
          }
          
          // 输出第一个任务的完整数据结构
          if (taskList.length > 0) {
            console.log('第一个任务的完整数据:', JSON.stringify(taskList[0]));
          }
          
          // 转换任务数据为组件使用的格式
          this.tasks = taskList.map(task => {
            // 确保taskStatus是数字
            let taskStatus = null;
            
            if (task.taskStatus !== undefined) {
              taskStatus = Number(task.taskStatus);
              console.log(`任务 ${task.id || task.taskId}: 原始taskStatus=${task.taskStatus}, 转换后=${taskStatus}, 类型=${typeof taskStatus}`);
            } else if (task.status !== undefined) {
              taskStatus = Number(task.status);
              console.log(`任务 ${task.id || task.taskId}: 使用status=${task.status}, 转换后=${taskStatus}, 类型=${typeof taskStatus}`);
            } else {
              taskStatus = 0;
              console.log(`任务 ${task.id || task.taskId}: 未找到状态字段，默认使用0`);
            }
            
            return {
              id: task.id || task.taskId || '未知ID',
              title: task.taskName || task.title || '未命名',
              category: this.mapTypeToCategory(task.taskType || task.type, task.categoryId),
              difficulty: task.taskDifficulty || task.difficulty || 0,
              startTime: task.startTime || '未设置',
              endTime: task.endTime || '未设置',
              // 显式转换为数字并赋值
              taskStatus: taskStatus,
              // 硬编码测试值 - 前端强制赋值测试
              taskStatusTest: 0,
              participants: task.hot || task.participantCount || task.participants || 0,
              pointsReward: task.points || task.pointReward || task.pointsReward || 0
            }
          })
          
          this.totalItems = totalCount || taskList.length
        })
        .catch(error => {
          console.error('获取任务列表失败:', error)
          // 出错时不改变当前数据，保留现有显示
        })
        .finally(() => {
          this.loading = false
        })
    },
    mapTypeToCategory(type, categoryId) {
      // 根据后端类型转为前端分类
      if (categoryId !== undefined) {
        // 优先使用分类ID
        const categoryIdMap = {
          1: 'daily',
          2: 'recycling',
          3: 'energy',
          4: 'transport',
          5: 'water'
        }
        return categoryIdMap[categoryId] || 'daily'
      }
      
      // 兼容旧代码，使用类型名称
      const typeMap = {
        '低碳生活': 'daily',
        '资源回收': 'recycling',
        '节能减排': 'energy',
        '绿色出行': 'transport',
        '节约用水': 'water'
      }
      
      return typeMap[type] || 'daily'
    },
    getCategoryId(category) {
      // 将前端分类转为分类ID
      const categoryMap = {
        'daily': 1,
        'recycling': 2,
        'energy': 3,
        'transport': 4,
        'water': 5
      }
      
      return categoryMap[category] || 1
    },
    mapStatusToString(status) {
      // 将数字状态转为字符串状态
      console.log('映射状态值:', status, '类型:', typeof status);
      
      // 显式检查是否为数字0 (不信任隐式转换)
      if (status === 0 || status === '0') {
        console.log('检测到状态为0，返回upcoming');
        return 'upcoming';
      }
      
      if (typeof status === 'number') {
        switch(status) {
          case 0: return 'upcoming';
          case 1: return 'active';
          case 2: return 'completed';
          default: return 'active';
        }
      }
      return status || 'active';
    },
    getCategoryText(category) {
      const categoryMap = {
        'daily': '日常生活',
        'energy': '节能减排',
        'transport': '绿色出行',
        'recycling': '垃圾分类',
        'water': '节约用水'
      }
      return categoryMap[category] || '未分类'
    },
    getStatusText(status) {
      const statusMap = {
        'active': '进行中',
        'completed': '已结束',
        'upcoming': '即将开始'
      }
      return statusMap[status] || '未知'
    },
    formatDate(dateString) {
      const date = new Date(dateString)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    },
    handleSearch() {
      this.currentPage = 1
      this.fetchTasks()
    },
    handleFilter() {
      this.currentPage = 1
      this.fetchTasks()
    },
    resetFilters() {
      this.searchQuery = ''
      this.statusFilter = ''
      this.categoryFilter = ''
      this.currentPage = 1
      this.fetchTasks()
    },
    changePage(page) {
      this.currentPage = page
      this.fetchTasks()
    },
    exportData() {
      // 实际应用中会调用导出API
      this.showNotification('导出数据功能将在实际应用中实现', 'info')
    },
    showDeleteConfirm(task) {
      this.selectedTask = task
      this.showDeleteModal = true
    },
    cancelDelete() {
      this.showDeleteModal = false
      this.selectedTask = {}
    },
    confirmDelete() {
      this.loading = true
      
      deleteTask(this.selectedTask.id)
        .then(response => {
          console.log('删除任务成功:', response)
          
          // 从列表中移除已删除的任务
          const index = this.tasks.findIndex(c => c.id === this.selectedTask.id)
      if (index !== -1) {
            this.tasks.splice(index, 1)
      }
      
      this.showDeleteModal = false
          this.selectedTask = {}
          
          // 显示成功消息，使用自定义通知带上alertMessage或默认消息
          const successMessage = response.alertMessage || '删除任务成功';
          this.showNotification(successMessage)
          
          // 刷新列表数据
          this.fetchTasks()
        })
        .catch(error => {
          console.error('删除任务失败:', error)
          this.showNotification(`删除任务失败: ${error.message || '未知错误'}`, 'error')
        })
        .finally(() => {
          this.loading = false
        })
    },
    showEditModal(task) {
      this.editingTask = task
      this.editModalVisible = true
      this.editErrors = {}
      
      // 获取任务详情
      this.fetchTaskDetails(task.id)
    },
    cancelEdit() {
      this.editModalVisible = false
      this.editingTask = {}
      this.editForm = {
        title: '',
        category: '',
        difficulty: 1,
        startTime: '',
        endTime: '',
        description: '',
        status: 'active',
        pointsReward: 100
      }
      this.editErrors = {}
      this.editError = null
    },
    fetchTaskDetails(id) {
      this.editLoading = true
      
      getTaskDetail(Number(id))
        .then(response => {
          console.log('获取任务详情成功:', response)
          
          // 检查响应
          if (response.code === 200 && response.data) {
            const taskData = response.data
            console.log('任务详情状态:', taskData.taskStatus, typeof taskData.taskStatus)
            
            // 填充表单数据
            this.editForm = {
              title: taskData.taskName || '',
              category: this.mapTypeToCategory(taskData.taskType || '', taskData.categoryId),
              difficulty: taskData.taskDifficulty !== undefined ? taskData.taskDifficulty : 0,
              startTime: taskData.startTime || '',
              endTime: taskData.endTime || '',
              description: taskData.taskDescription || '',
              status: this.mapStatusToString(taskData.taskStatus),
              rawStatus: taskData.taskStatus, // 保存原始状态值
              pointsReward: taskData.points !== undefined ? taskData.points : 100
            }
          } else {
            this.editError = '获取任务数据失败'
          }
        })
        .catch(error => {
          console.error('获取任务详情失败:', error)
          this.editError = `获取任务数据出错: ${error.message || '未知错误'}`
        })
        .finally(() => {
          this.editLoading = false
        })
    },
    validateEditForm() {
      this.editErrors = {}
      
      // 基本信息验证
      if (!this.editForm.title) {
        this.editErrors.title = '请输入任务名称'
      }
      
      if (!this.editForm.category) {
        this.editErrors.category = '请选择任务类型'
      }
      
      if (!this.editForm.difficulty) {
        this.editErrors.difficulty = '请选择难度级别'
      }
      
      if (!this.editForm.startTime) {
        this.editErrors.startTime = '请选择开始时间'
      }
      
      if (!this.editForm.endTime) {
        this.editErrors.endTime = '请选择结束时间'
      } else if (this.editForm.startTime && new Date(this.editForm.endTime) <= new Date(this.editForm.startTime)) {
        this.editErrors.endTime = '结束时间必须晚于开始时间'
      }
      
      if (!this.editForm.description) {
        this.editErrors.description = '请输入任务描述'
      }
      
      // 积分验证
      if (typeof this.editForm.pointsReward !== 'number' || this.editForm.pointsReward < 0) {
        this.editErrors.pointsReward = '积分奖励必须是大于等于0的数字'
      }
      
      return Object.keys(this.editErrors).length === 0
    },
    saveEdit() {
      if (!this.validateEditForm()) {
        return
      }
      
      this.editLoading = true
      
      // 获取当前的数字状态
      const taskStatus = this.mapStringToStatus(this.editForm.status)
      console.log('保存编辑 - 状态:', this.editForm.status, '数字状态:', taskStatus)
      
      // 构建API需要的数据格式，与后端TaskDTO匹配
      const taskDTO = {
        id: Number(this.editingTask.id),
        taskName: this.editForm.title,
        categoryId: this.getCategoryId(this.editForm.category),
        taskDifficulty: this.editForm.difficulty,
        startTime: this.editForm.startTime,
        endTime: this.editForm.endTime,
        taskDescription: this.editForm.description,
        taskStatus: taskStatus,
        points: this.editForm.pointsReward,
        hot: this.editingTask.participants
      }
      
      updateTask(taskDTO)
        .then(response => {
          console.log('更新任务成功:', response)
          
          // 更新本地列表中的数据
          const index = this.tasks.findIndex(c => c.id === this.editingTask.id)
          if (index !== -1) {
            this.tasks[index] = {
              ...this.tasks[index],
              title: this.editForm.title,
              category: this.editForm.category,
              difficulty: this.editForm.difficulty,
              startTime: this.editForm.startTime,
              endTime: this.editForm.endTime,
              status: this.editForm.status,
              rawStatus: taskStatus, // 更新原始状态值
              pointsReward: this.editForm.pointsReward
            }
          }
          
          // 关闭弹窗并显示成功消息
          this.cancelEdit()
          this.showNotification('任务更新成功')
          
          // 刷新列表
          this.fetchTasks()
        })
        .catch(error => {
          console.error('更新任务失败:', error)
          this.showNotification(`更新任务失败: ${error.message || '未知错误'}`, 'error')
        })
        .finally(() => {
          this.editLoading = false
        })
    },
    mapCategoryToType(category) {
      // 从前端分类转为后端类型
      const categoryMap = {
        'daily': '低碳生活',
        'recycling': '资源回收',
        'energy': '节能减排',
        'transport': '绿色出行',
        'water': '节约用水'
      }
      
      return categoryMap[category] || '低碳生活'
    },
    mapStringToStatus(str) {
      // 将字符串状态转为数字状态
      const statusMap = {
        'upcoming': 0,
        'active': 1,
        'completed': 2
      }
      
      return statusMap[str] !== undefined ? statusMap[str] : 1
    },
    getDifficultyDisplay(difficulty) {
      // 将后端难度值转为前端显示值（+1）
      return Math.min(difficulty, 2);
    },
    // 显示通知的辅助方法
    showNotification(message, type = 'success', duration = 3000) {
      // 清除之前的定时器
      if (this.notification.timeout) {
        clearTimeout(this.notification.timeout);
      }
      
      // 设置新通知
      this.notification.show = true;
      this.notification.message = message;
      this.notification.type = type;
      
      // 自动关闭通知
      this.notification.timeout = setTimeout(() => {
        this.notification.show = false;
      }, duration);
    },
    getTaskStatusText(status) {
      console.log('getTaskStatusText被调用，参数:', status, '类型:', typeof status);
      
      // 将状态转换为数字以确保一致性
      const numStatus = Number(status);
      console.log('numStatus:', numStatus, '类型:', typeof numStatus, '是NaN:', isNaN(numStatus));
      
      // 显式检查具体的数值
      if (numStatus === 0) {
        return '即将开始 (0)';
      } else if (numStatus === 1) {
        return '进行中 (1)';
      } else if (numStatus === 2) {
        return '已结束 (2)';
      } else {
        return `未知状态 (${status})`;
      }
    },
    getStatusClass(status) {
      console.log('getStatusClass被调用，参数:', status);
      
      // 将状态转换为数字以确保一致性
      const numStatus = Number(status);
      
      // 显式检查具体的数值
      if (numStatus === 0) {
        return 'status-tag status-upcoming';
      } else if (numStatus === 1) {
        return 'status-tag status-active';
      } else if (numStatus === 2) {
        return 'status-tag status-completed';
      } else {
        return 'status-tag';
      }
    }
  }
}
</script>

<style scoped>
.admin-challenges {
  display: flex;
  flex-direction: column;
  gap: 24px;
  width: 100%;
  min-height: 100%;
  padding: 0;
}

/* 猫咪动画样式 */
.cat-animation-container {
  position: relative;
  height: 200px;
  margin: 0;
  overflow: hidden;
  background-color: rgba(240, 248, 255, 0.5);
  border-radius: 0;
  box-shadow: inset 0 0 10px rgba(0,0,0,0.05);
}

.cat {
  position: absolute;
  bottom: 20px;
  left: 50px;
  width: 80px;
  height: 70px;
  animation: cat-walk 15s infinite linear;
}

@keyframes cat-walk {
  0% { left: -80px; transform: scaleX(1); }
  45% { left: calc(50% - 100px); transform: scaleX(1); }
  50% { left: calc(50% - 80px); transform: scaleX(-1); }
  95% { left: -50px; transform: scaleX(-1); }
  100% { left: -80px; transform: scaleX(1); }
}

.cat-head {
  position: relative;
  width: 50px;
  height: 45px;
  background-color: #a0704e;
  border-radius: 50%;
  z-index: 2;
}

.cat-ears {
  position: absolute;
  top: -10px;
  width: 100%;
}

.cat-ear {
  position: absolute;
  width: 0;
  height: 0;
  border-bottom: 20px solid #a0704e;
  border-left: 10px solid transparent;
  border-right: 10px solid transparent;
}

.cat-ear.left {
  left: 0;
  transform: rotate(-30deg);
}

.cat-ear.right {
  right: 0;
  transform: rotate(30deg);
}

.cat-face {
  position: relative;
  padding-top: 10px;
}

.cat-eyes {
  display: flex;
  justify-content: space-around;
  margin-bottom: 5px;
}

.cat-eye {
  width: 8px;
  height: 12px;
  background-color: #000;
  border-radius: 50%;
  animation: cat-blink 3s infinite;
}

@keyframes cat-blink {
  0%, 96%, 100% { transform: scaleY(1); }
  98% { transform: scaleY(0.1); }
}

.cat-nose {
  width: 8px;
  height: 5px;
  background-color: #ff9999;
  border-radius: 50%;
  margin: 3px auto;
}

.cat-mouth {
  width: 8px;
  height: 3px;
  border-bottom: 2px solid #333;
  border-radius: 50%;
  margin: 2px auto;
}

.cat-whiskers {
  position: absolute;
  top: 15px;
  width: 100%;
}

.whisker {
  position: absolute;
  width: 15px;
  height: 1px;
  background-color: #555;
}

.w1 {
  top: 0;
  left: -15px;
  transform: rotate(-10deg);
}

.w2 {
  top: 5px;
  left: -15px;
}

.w3 {
  top: 10px;
  left: -15px;
  transform: rotate(10deg);
}

.w4 {
  top: 0;
  right: -15px;
  transform: rotate(10deg);
}

.w5 {
  top: 5px;
  right: -15px;
}

.w6 {
  top: 10px;
  right: -15px;
  transform: rotate(-10deg);
}

.cat-body {
  position: relative;
  top: -15px;
  width: 60px;
  height: 40px;
  background-color: #a0704e;
  border-radius: 50% 50% 50% 50% / 60% 60% 40% 40%;
}

.cat-tail {
  position: absolute;
  right: -20px;
  bottom: 15px;
  width: 40px;
  height: 10px;
  background-color: #a0704e;
  border-radius: 0 5px 5px 0;
  transform-origin: 0 50%;
  animation: tail-wag 2s infinite ease-in-out;
}

@keyframes tail-wag {
  0%, 100% { transform: rotate(0deg); }
  50% { transform: rotate(20deg); }
}

.cat-paws {
  position: absolute;
  bottom: -8px;
  width: 100%;
  display: flex;
  justify-content: space-around;
}

.cat-paw {
  width: 12px;
  height: 10px;
  background-color: #d3a77c;
  border-radius: 50%;
  animation: paw-move 0.5s infinite alternate;
}

.cat-paw:first-child {
  animation-delay: 0.25s;
}

@keyframes paw-move {
  0% { transform: translateY(0); }
  100% { transform: translateY(-5px); }
}

.yarn-ball {
  position: absolute;
  bottom: 20px;
  right: 100px;
  width: 30px;
  height: 30px;
  background-color: #4da6ff;
  border-radius: 50%;
  animation: yarn-roll 15s infinite linear;
}

@keyframes yarn-roll {
  0% { right: 100%; transform: rotate(0deg); }
  45% { right: calc(50% + 100px); transform: rotate(720deg); }
  50% { right: calc(50% + 80px); }
  95% { right: 0%; transform: rotate(1440deg); }
  100% { right: -50px; }
}

.eco-message {
  position: absolute;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(255, 255, 255, 0.9);
  padding: 10px 20px;
  border-radius: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 16px;
  color: #1890ff;
}

.eco-icon {
  font-size: 20px;
  animation: grow-shrink 2s infinite ease-in-out;
}

@keyframes grow-shrink {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.2); }
}

/* 工具栏样式 */
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 16px 24px;
  flex-wrap: wrap;
  gap: 16px;
}

.search-box {
  position: relative;
  min-width: 250px;
}

.search-input {
  padding-right: 40px;
}

.search-btn {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  cursor: pointer;
  font-size: 16px;
}

.filter-options {
  display: flex;
  gap: 16px;
}

.filter-select {
  min-width: 120px;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

/* 任务列表样式 */
.challenges-list {
  width: 100%;
  overflow-x: auto;
  padding: 0 24px;
}

.difficulty-wrapper {
  display: flex;
  gap: 4px;
}

.difficulty-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #f0f0f0;
}

.difficulty-dot.active {
  background-color: #faad14;
}

.status-tag {
  display: inline-block;
  padding: 4px 12px;
  border-radius: 4px;
  font-size: 14px;
  font-weight: bold;
  line-height: 1.4;
}

.status-active {
  background-color: #e6f7ff;
  color: #1890ff;
  border: 1px solid #91d5ff;
}

.status-completed {
  background-color: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.status-upcoming {
  background-color: #fff7e6;
  color: #fa8c16;
  border: 1px solid #ffd591;
}

.status-debug {
  display: block;
  font-size: 11px;
  opacity: 0.7;
  font-weight: normal;
  margin-top: 2px;
}

.actions-cell {
  text-align: center;
}

.actions-wrapper {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.action-btn {
  padding: 2px 8px;
  border-radius: 2px;
  font-size: 12px;
  cursor: pointer;
  text-decoration: none;
  border: none;
}

.edit-btn {
  background-color: #e6f7ff;
  color: #1890ff;
  border: 1px solid #91d5ff;
}

.delete-btn {
  background-color: #fff1f0;
  color: #ff4d4f;
  border: 1px solid #ffa39e;
}

.empty-message {
  padding: 40px 0;
  text-align: center;
}

.empty-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.empty-icon {
  font-size: 32px;
  color: #d9d9d9;
}

.empty-text {
  color: rgba(0, 0, 0, 0.45);
}

/* 分页器样式 */
.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 16px 24px;
  flex-wrap: wrap;
  gap: 16px;
}

.pagination-info {
  color: rgba(0, 0, 0, 0.45);
  font-size: 14px;
}

.pagination-buttons {
  display: flex;
  gap: 8px;
}

.pagination-btn {
  min-width: 32px;
  height: 32px;
  padding: 0 8px;
  border: 1px solid #d9d9d9;
  border-radius: 2px;
  background-color: white;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: all 0.3s;
}

.pagination-btn:hover:not(:disabled) {
  color: #1890ff;
  border-color: #1890ff;
}

.pagination-btn.active {
  color: white;
  background-color: #1890ff;
  border-color: #1890ff;
}

.pagination-btn:disabled {
  color: rgba(0, 0, 0, 0.25);
  background-color: #f5f5f5;
  cursor: not-allowed;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.45);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-container {
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  width: 400px;
  animation: modalFadeIn 0.3s;
}

@keyframes modalFadeIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.modal-header {
  padding: 16px 24px;
  border-bottom: 1px solid #f0f0f0;
}

.modal-header h3 {
  margin: 0;
  font-size: 16px;
  color: rgba(0, 0, 0, 0.85);
}

.modal-body {
  padding: 24px;
}

.warning-text {
  color: #ff4d4f;
  font-size: 14px;
}

.modal-footer {
  padding: 10px 16px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

/* 编辑弹窗样式 */
.edit-modal {
  width: 700px;
  max-width: 90vw;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: rgba(0, 0, 0, 0.45);
}

.modal-close-btn:hover {
  color: rgba(0, 0, 0, 0.75);
}

.edit-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.form-row {
  margin-bottom: 16px;
}

.form-row.two-col {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.admin-form-label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
}

.admin-form-label.required::after {
  content: '*';
  color: #ff4d4f;
  margin-left: 4px;
}

.admin-form-input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 2px;
  transition: all 0.3s;
}

.admin-form-input:focus {
  border-color: #40a9ff;
  outline: none;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.admin-form-error {
  margin-top: 4px;
  color: #ff4d4f;
  font-size: 14px;
}

.description-input {
  resize: vertical;
}

.difficulty-selector {
  display: flex;
  gap: 16px;
}

.difficulty-option {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
  cursor: pointer;
  transition: all 0.3s;
  font-weight: 500;
}

.difficulty-option:hover {
  background-color: #e6f7ff;
}

.difficulty-option.active {
  background-color: #1890ff;
  color: white;
}

.status-selector {
  display: flex;
  gap: 24px;
}

.status-option {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.status-option input {
  margin-right: 8px;
}

@media (max-width: 768px) {
  .form-row.two-col {
    grid-template-columns: 1fr;
  }
  
  .status-selector {
    flex-direction: column;
    gap: 12px;
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .search-box {
    width: 100%;
  }
  
  .filter-options {
    width: 100%;
  }
  
  .action-buttons {
    width: 100%;
  }
  
  .pagination {
    flex-direction: column;
    align-items: flex-start;
  }
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 8px;
  margin: 20px 0;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(24, 144, 255, 0.2);
  border-radius: 50%;
  border-top-color: #1890ff;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.empty-message {
  text-align: center;
  padding: 40px 0 !important;
}

.empty-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}

.empty-icon {
  font-size: 36px;
  color: #d9d9d9;
}

.empty-text {
  font-size: 16px;
  color: #8c8c8c;
}

.empty-action {
  margin-top: 8px;
}

/* 通知样式 */
.notification-container {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 2000;
  max-width: 350px;
  animation: slideIn 0.3s ease-out;
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

.notification {
  padding: 12px 16px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.2);
  margin-bottom: 12px;
}

.notification-success {
  background-color: #f6ffed;
  border: 1px solid #b7eb8f;
  color: #52c41a;
}

.notification-error {
  background-color: #fff1f0;
  border: 1px solid #ffa39e;
  color: #ff4d4f;
}

.notification-info {
  background-color: #e6f7ff;
  border: 1px solid #91d5ff;
  color: #1890ff;
}

.notification-message {
  font-size: 14px;
  flex: 1;
}

.notification-close {
  background: none;
  border: none;
  font-size: 18px;
  cursor: pointer;
  color: rgba(0, 0, 0, 0.45);
  margin-left: 12px;
}

.notification-close:hover {
  color: rgba(0, 0, 0, 0.75);
}

.status-code {
  font-size: 12px;
  opacity: 0.9;
  margin-left: 4px;
  font-weight: normal;
}

.status-text {
  font-weight: bold;
}

.debug-status {
  display: flex;
  flex-direction: column;
  border: 1px solid #ccc;
  padding: 4px;
  font-size: 12px;
  background-color: #f9f9f9;
  color: #333;
}

.debug-status span {
  margin: 2px 0;
  word-break: break-all;
}

.status-detail {
  font-size: 12px;
  color: rgba(0, 0, 0, 0.55);
  margin-left: 4px;
  font-weight: normal;
}
</style> 